<?php
namespace config;


use core\utils\Bean;
use core\utils\RouterRule;

class Mapping implements Bean
{
    /**
     * 用来存放路由规则的
     * @var RouterRule[]
     */
    private $rules = [];
    private static $instance = null;
    /**
     * @var RouterRule 匹配上的RouterRule
     */
    private $routerRule;

    private function __construct() {
        foreach ($this->rules as $key=>$row) {
            unset($this->rules[$key]);
            $rule = new RouterRule($row[0], $row[1], $row[2] ?? null);
            $this->rules[$rule->getUrl()] = $rule;
        }
    }

    public static function getInstance() {
        if (null === self::$instance)
            self::$instance = new self();
        return self::$instance;
    }

    /**
     * 是否含有指定的url对应的Rule
     * @param string $url
     * @return bool
     */
    public function contain(string $url) : bool {
        if ($this->routerRule)
            return true;

        foreach ($this->rules as $rule) {
            if ($rule->match($url)) {
                $this->routerRule = $rule;
                return true;
            }
        }
        return false;
    }

    /**
     * 在这里不做key不存在的校验了，
     * 交给上级吧。。
     * @param $url string
     * @return RouterRule
     */
    public function getRule(string $url) : RouterRule {
        return $this->routerRule;
    }

    /**
     * @param $url
     * @param $method
     * @return bool|string
     */
    public function getTrueUrl(string $url, string $method) {
        if ('' == $url) {
            $url = '/';
        }
        if ($this->contain($url)) {
            $method = strtoupper($method);
            if ($this->routerRule->getMethod() === 'ALL' || $method == $this->routerRule->getMethod()) {
                return $this->routerRule->getTrueUrl();
            } else {
                return false;
            }
        } else {
            return $url;
        }
    }
}